package io.gitee.duxiuhuan.mailbox.service.impl;

import io.gitee.duxiuhuan.mailbox.database.QueryTableMapper;
import io.gitee.duxiuhuan.mailbox.service.inter.QueryTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class QueryTableService implements QueryTable {
    
    @Autowired
    private QueryTableMapper queryTableMapper;

    @Value("${spring.datasource.url}")
    private String datasourceUrl;
    
    @Override
    public Boolean createTable(String tableName) {
        try {
            queryTableMapper.createTable(tableName, datasourceUrl.contains("postgresql") ? "pgsql" : "mysql");
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    
    @Override
    public Boolean dropTable(String tableName) {
        try {
            queryTableMapper.dropTable(tableName, datasourceUrl.contains("postgresql") ? "pgsql" : "mysql");
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    
    @Override
    public Boolean updateTable(String oldTableName, String newTableName) {
        try {
            queryTableMapper.renameTable(oldTableName, newTableName, datasourceUrl.contains("postgresql") ? "pgsql" : "mysql");
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    
    @Override
    public List<String> selectTable(String tableName) {
        try {
            List<String> tablesByPattern = queryTableMapper.getTablesByPattern(tableName, datasourceUrl.contains("postgresql") ? "pgsql" : "mysql");
            return tablesByPattern;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
